#include "bsp_timer2.h"
#include "key.h"

timer2_fc_t timer2_fc = {0};

void bsp_timer2_init(void)
{
    /* clk 配置 */
    NVIC_InitTypeDef NVIC_InitStructure;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    /* timer 配置 */
    TIM_TimeBaseStructure.TIM_Period = 10 - 1;              // 计数值
    TIM_TimeBaseStructure.TIM_Prescaler = 32000 - 1;        // 分频值
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; // 分频系数
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

    /* nvic 配置 */
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
    TIM_Cmd(TIM2, ENABLE);
}

void TIM2_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
    {
        key_process(); // 按键处理

        /* ************************************** 20ms周期阶段性触发 ************************************** */
        if (++timer2_fc.trgger_cnt_20ms >= 2)
        {
            timer2_fc.trgger_20 = 1;
            timer2_fc.trgger_cnt_20ms = 0;
        }

        /* ************************************** 100ms周期阶段性触发 ************************************** */
        if (++timer2_fc.trgger_cnt_200ms >= 20)
        {
            timer2_fc.trgger_200 = 1;
            timer2_fc.trgger_cnt_200ms = 0;
        }

        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
    }
}
